<template>
  <span v-if="addZero">{{ day + '天' + hourString + '时' + minuteString + '分' + secondString + '秒' }}</span>
  <span v-else>{{ day + '天' + hour + '时' + min + '分' + sec + '秒' }}</span>
</template>

<script lang="ts" setup>
import {computed, onBeforeUnmount, ref} from "vue";

const prop = defineProps({
  remainTime: {    // 倒计时间总秒数
    default: 0,
    required: true
  },
  addZero: {    // 是否需要加零
    default: false
  }
})
const emit = defineEmits(['count-down-end'])
const day = ref(0)
const hour = ref(0)
const min = ref(0)
const sec = ref(0)
const timer = ref<any>(null)
if (prop.remainTime > 0) {
  day.value = Math.floor(prop.remainTime / 3600 / 24)
  hour.value = Math.floor((prop.remainTime / 3600) % 24)
  min.value = Math.floor((prop.remainTime / 60) % 60)
  sec.value = Math.floor(prop.remainTime % 60)
  countDown()
}

function countDown() {
  timer.value = setInterval(() => {
    sec.value--
    if (sec.value === -1) {
      sec.value = 59
      min.value--
      if (min.value === -1) {
        min.value = 59
        hour.value--
        if (hour.value === -1) {
          hour.value = 23
          day.value--
          if (day.value === -1) {
            clearInterval(timer.value)
            emit('count-down-end', true)
          }
        }
      }
    }
  }, 1000)
}

function formatNum(num: number) {
  return num < 10 ? '0' + num : '' + num
}

const hourString = computed(() => {
  return formatNum(hour.value)
})
const minuteString = computed(() => {
  return formatNum(min.value)
})
const secondString = computed(() => {
  return formatNum(sec.value)
})
onBeforeUnmount(() => {
  clearInterval(timer.value);
})
</script>
